package com.market.sys.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.market.sys.common.Result;
import com.market.sys.entity.Article;
import com.market.sys.entity.UserCollection;
import com.market.sys.entity.UserLike;
import com.market.sys.mapper.ArticleMapper;
import com.market.sys.mapper.UserCollectionMapper;
import com.market.sys.mapper.UserLikeMapper;
import com.market.sys.service.IArticleService;
import com.market.sys.util.Constants;
import com.market.sys.util.EmptyUtil;
import com.market.sys.util.TimeUtil;
import com.market.sys.vo.ArticleVO;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author xd
 * @since 2024-03-26
 */
@Service
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article> implements IArticleService {

    @Resource
    private UserCollectionMapper userCollectionMapper;

    @Resource
    private UserLikeMapper userLikeMapper;

    @Override
    public Result<?> findByCondition(Map<String, Object> conditionMap) {
        // 创建一个分页对象，pageNum和pageSize从conditionMap中获取并转换为Long类型
        Page<Article> page = new Page<>((int) conditionMap.get("pageNum"), (int) conditionMap.get("pageSize"));

        // 创建Lambda查询条件构造器
        LambdaQueryWrapper<Article> lambdaQueryWrapper = new LambdaQueryWrapper<>();

        // 如果条件中的标题不为空，则加入标题的等值查询条件
        if (!EmptyUtil.isStringEmpty(String.valueOf(conditionMap.get("title")))) {
            lambdaQueryWrapper.like(Article::getTitle, String.valueOf(conditionMap.get("title")));
        }

        // 按发布时间倒序排序
        lambdaQueryWrapper.orderByDesc(Article::getPublishTime);

        // 根据分页对象和查询条件执行分页查询
        Page<Article> articlePage = this.baseMapper.selectPage(page, lambdaQueryWrapper);

        // 将Article类型的分页结果转换为ArticleVO类型的列表
        List<ArticleVO> articleVOList = new ArrayList<>();
        for (Article article : articlePage.getRecords()) {
            ArticleVO articleVO = new ArticleVO();

            // 将Article的属性拷贝到ArticleVO中
            BeanUtil.copyProperties(article, articleVO, false);

            // 处理封面图片的逻辑
            // 将封面图片字符串按逗号分割成数组
            String[] imageArr = article.getCoverImage().split(",");
            List<String> imgList = new ArrayList<>();
            if (!EmptyUtil.isStringEmpty(article.getCoverImage())){
                for (String img : imageArr) {
                    // 添加下载链接前缀，并加入到图片链接列表中
                    imgList.add(Constants.DOWNLOAD_URL + img);
                }
            }

            // 将处理后的图片链接列表设置到ArticleVO中
            articleVO.setCoverImageList(imgList);

            articleVO.setPublishTime(TimeUtil.completeGetTimeStamp(articleVO.getPublishTime()));

            // 将处理后的ArticleVO对象加入到列表中
            articleVOList.add(articleVO);
        }

        // 封装返回的数据，包括文章列表和总数
        Map<String, Object> data = new HashMap<>(2);

        // 文章列表
        data.put("list", articleVOList);

        // 文章总数
        data.put("total", articlePage.getTotal());

        // 返回成功结果
        return Result.success(data);
    }

    @Override
    public Result<?> fetchCollectList(Map<String, Object> conditionMap) {
        int pageNum = (int)conditionMap.get("pageNum");
        int pageSize = (int)conditionMap.get("pageSize");
        Page<UserCollection> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<UserCollection> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(UserCollection::getUserId,conditionMap.get("userId"))
                .eq(UserCollection::getType, conditionMap.get("type"))
                .orderByDesc(UserCollection::getCollectTime);
        Page<UserCollection> userCollectionPage = userCollectionMapper.selectPage(page, lambdaQueryWrapper);

        List<ArticleVO> articleVOList = new ArrayList<>();
        for (UserCollection userCollection : userCollectionPage.getRecords()) {
            ArticleVO articleVO = new ArticleVO();
            Article article = this.baseMapper.selectOne(new LambdaQueryWrapper<Article>().eq(Article::getId, userCollection.getThingId()));

            // 将Article的属性拷贝到ArticleVO中
            BeanUtil.copyProperties(article, articleVO, false);

            // 处理封面图片的逻辑
            // 将封面图片字符串按逗号分割成数组
            String[] imageArr = article.getCoverImage().split(",");
            List<String> imgList = new ArrayList<>();
            if (!EmptyUtil.isStringEmpty(article.getCoverImage())){
                for (String img : imageArr) {
                    // 添加下载链接前缀，并加入到图片链接列表中
                    imgList.add(Constants.DOWNLOAD_URL + img);
                }
            }

            // 将处理后的图片链接列表设置到ArticleVO中
            articleVO.setCoverImageList(imgList);

            articleVO.setPublishTime(TimeUtil.completeGetTimeStamp(articleVO.getPublishTime()));

            // 将处理后的ArticleVO对象加入到列表中
            articleVOList.add(articleVO);
        }
        return Result.success(articleVOList);
    }

    @Override
    public Result<?> fetchLikeList(Map<String, Object> conditionMap) {
        int pageNum = (int)conditionMap.get("pageNum");
        int pageSize = (int)conditionMap.get("pageSize");
        Page<UserLike> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<UserLike> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(UserLike::getUserId,conditionMap.get("userId"))
                .eq(UserLike::getType, conditionMap.get("type"))
                .orderByDesc(UserLike::getLikeTime);
        Page<UserLike> userLikePage = userLikeMapper.selectPage(page, lambdaQueryWrapper);

        List<ArticleVO> articleVOList = new ArrayList<>();
        for (UserLike userLike : userLikePage.getRecords()) {
            ArticleVO articleVO = new ArticleVO();
            Article article = this.baseMapper.selectOne(new LambdaQueryWrapper<Article>().eq(Article::getId, userLike.getThingId()));

            // 将Article的属性拷贝到ArticleVO中
            BeanUtil.copyProperties(article, articleVO, false);

            // 处理封面图片的逻辑
            // 将封面图片字符串按逗号分割成数组
            String[] imageArr = article.getCoverImage().split(",");
            List<String> imgList = new ArrayList<>();
            if (!EmptyUtil.isStringEmpty(article.getCoverImage())){
                for (String img : imageArr) {
                    // 添加下载链接前缀，并加入到图片链接列表中
                    imgList.add(Constants.DOWNLOAD_URL + img);
                }
            }

            // 将处理后的图片链接列表设置到ArticleVO中
            articleVO.setCoverImageList(imgList);

            articleVO.setPublishTime(TimeUtil.completeGetTimeStamp(articleVO.getPublishTime()));

            // 将处理后的ArticleVO对象加入到列表中
            articleVOList.add(articleVO);
        }
        return Result.success(articleVOList);
    }
}
